package com.qpx.jxcgateway.filter;

import com.alibaba.nacos.client.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qpx.jxc.common.vo.ResultEntity;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class TestGatewayFilter implements GlobalFilter {
    private final ObjectMapper objectMapper;

    @Value("${test.url}")
    private String url;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 不是登录请求，直接向下执行
        log.info("gateway ValidateCodeGatewayFilter 过滤器 请求的地址为:{}", request.getURI().getPath());
        if (StringUtils.isNotBlank(url)){
            List<String> urls = Arrays.asList(url.split(","));
            if (urls.contains(request.getURI().getPath())){//请求包含活动限流的url地址

                //业务逻辑根据自己的需求自行设计，我这里是直接返回异常
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.NOT_IMPLEMENTED);
                try {
                    return response.writeWith(Mono.just(response.bufferFactory()
                            .wrap(objectMapper.writeValueAsBytes(ResultEntity.error("限流拒绝访问", null)))));
                } catch (JsonProcessingException e1) {
                    log.error("对象输出异常", e1);
                }
            }
        }
        //放行
        return chain.filter(exchange);
    }
}
